<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\GenderConstants;
use App\Common\Constants\RemarkMatchTypeConstants;
use App\Common\Constants\TagMathTypeConstants;
use App\Common\Helpers\VideoHelper;
use App\Common\Robot\Contracts\GatewayInterface;
use App\Common\Robot\Robot;
use App\CustHub\Amqp\Producers\CommonProducers;
use App\CustHub\Constants\FrdCircTaskContentTypeConstants;
use App\CustHub\Constants\FrdCircTaskSendStatusConstants;
use App\CustHub\Constants\FrdCircTaskStatusConstants;
use App\CustHub\Dto\CommonProducersDto;
use App\CustHub\Mapper\ChFriendCircleTaskMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChFriendCircleTask;
use App\CustHub\Model\ChFriendCircleTaskSendRecord;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChSmartTag;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\RobotApiService;
use Carbon\Carbon;
use Hyperf\Amqp\Producer;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Coroutine\Exception\ParallelExecutionException;
use Hyperf\Coroutine\Parallel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use Mine\MineModel;
use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

/**
 * 朋友圈任务
 */
class ChFriendCircleTaskService extends AbstractService
{
    public $mapper;

    #[Inject]
    public ChRobotMapper $robotMapper;

    public function __construct(ChFriendCircleTaskMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function list(array $data)
    {
        $pageSize = data_get($data, 'page_size',MineModel::PAGE_SIZE);

        $query = $this->mapper->model::query()
            ->with(['user'=>function ($query) {
                $query->select(['id','nickname','parent_id']);
            },'group'=>function ($query) {
                $query->select(['id','name']);
            }])
            ->where('main_uid',$data['main_uid']);

        $paginate = $this->mapper
            ->handleSearch($query,$data)
            ->orderBy('created_at','desc')
            ->paginate((int)$pageSize);

        $paginate->getCollection()->transform(function ($item){

            $item->send_content_type = FrdCircTaskContentTypeConstants::getMessage($item->send_content['type']);
            $item->robot_count = count($item->robot_ids);
            $item->status_text = FrdCircTaskStatusConstants::getMessage($item->status);
            $item->user_name = $item->main_uid == $item->uid ? '主账号' : $item->user->username;
            $item->group_name =  $item->group_id == 0 ? '默认分组' : $item->group->name;
            unset($item->user,$item->group);

            $contactData = $item->contact_data;
            $config = $contactData['conf'] ?? [];

            $contactConfig = [];
            foreach ($config as $ck=>$confItem){
                $prefix = '';
                if(isset($confItem['op'])){
                    $prefix = $confItem['op'] == 'and' ? '且' : '或';
                }

                $arr = [
                    'title' => $prefix.'满足条件组'.((int)$ck+1)
                ];
                if(isset($confItem['isset'])){
                    $arr['sub'][] = [
                        'title' => '客户符合以下条件',
                        'data' => $this->formattedCustomerData($confItem['isset'])
                    ];
                }

                if(isset($confItem['exclude_switch']) && isset($confItem['out'])){
                    $arr['sub'][] = [
                        'title' => '客户排除以下条件',
                        'data' => $this->formattedCustomerData($confItem['out'])
                    ];
                }
                $contactConfig[] = $arr;
            }

            $item->contact_match_type = $contactData['type'];
            $item->contact_conf_data = $contactConfig;
            empty($item->comments) && $item->comments = [];
            if(!empty($item->exception_data)){
                $item->exception_data = implode(',',$item->exception_data);
            }else{
                $item->exception_data = '';
            }

            $item->send_time = datetime($item->send_time);
            return $item;
        });

        return $this->mapper->setPaginate($paginate);
    }

    public function getInfo(array $params)
    {
        $info = $this->mapper->model::query()
            ->with(['user'=>function ($query) {
                $query->select(['id','nickname','parent_id']);
            },'group'=>function ($query) {
                $query->select(['id','name']);
            }])
            ->where('id',$params['id'])
            ->first();

        if(empty($info)){
            throw new NormalStatusException('任务不存在');
        }

        $info->send_content_type = FrdCircTaskContentTypeConstants::getMessage($info->send_content['type']);
        $info->robot_count = count($info->robot_ids);
        if(!empty($info->robot_ids)){
            $info->robot_list = ChRobot::query()
                ->select(['id','nickname','avatar','corp_name','user_id','login_status'])
                ->whereIn('id',$info->robot_ids)
                ->get();
        }else{
            $info->robot_list = [];
        }
        $info->status_text = FrdCircTaskStatusConstants::getMessage($info->status);
        $info->user_name = $info->main_uid == $info->uid ? '主账号' : $info->user->username;
        $info->group_name =  $info->group_id == 0 ? '默认分组' : $info->group->name;
        unset($info->user,$info->group);

        $contactData = $info->contact_data;
        $config = $contactData['conf'] ?? [];

        $contactConfig = [];
        foreach ($config as $ck=>$confItem){
            $prefix = '';
            if(isset($confItem['op'])){
                $prefix = $confItem['op'] == 'and' ? '且' : '或';
            }

            $arr = [
                'title' => $prefix.'满足条件组'.((int)$ck+1)
            ];
            if(isset($confItem['isset'])){
                $arr['sub'][] = [
                    'title' => '客户符合以下条件',
                    'data' => $this->formattedCustomerData($confItem['isset'])
                ];
            }

            if(isset($confItem['exclude_switch']) && isset($confItem['out'])){
                $arr['sub'][] = [
                    'title' => '客户排除以下条件',
                    'data' => $this->formattedCustomerData($confItem['out'])
                ];
            }
            $contactConfig[] = $arr;
        }

        $info->contact_match_type = $contactData['type'];
        $info->contact_conf_data = $contactConfig;
        empty($info->comments) && $info->comments = [];
        if(!empty($info->exception_data)){
            $info->exception_data = implode(',',$info->exception_data);
        }else{
            $info->exception_data = '';
        }

        $sendTimeConfig = $info->send_time_config;
        if(empty($sendTimeConfig)){
            $sendTimeConfig = [
                "send_type" => $info->send_time_type,
                "send_time" => datetime($info->send_time),
                "num" => [],
                "isLoopEnded" => 0,
                "end_time" => ""
            ];
            $info->send_time_config = $sendTimeConfig;
        }

        $info->send_time_text = datetime($info->send_time);
        return $info;
    }

    /**
     * 下发机器人列表
     * @param array $data
     * @return array
     */
    public function robotList(array $data): array
    {

        $showFail = data_get($data,'show_fail',0);
        $robotId = data_get($data,'robot_id');

        $list = ChFriendCircleTaskSendRecord::query()
            ->select(['id','robot_id','friend_circle_status','comment_status'])
            ->with(['robot'=>function ($query) {
                $query->select(['id','nickname','avatar','corp_name','login_status']);
            }])
            ->when(!empty($robotId),function ($query) use ($robotId){
                $query->where('robot_id',$robotId);
            })
            ->when($showFail == 1,function ($query){
                $query->where('friend_circle_status',FrdCircTaskSendStatusConstants::FAILURE);
            })
            ->where('task_id',$data['id'])
            ->get()->toArray();
        return $list;
    }

    /**
     * 任务日历
     * @param $uid
     * @param $date
     * @param null $status
     */
    public function getTaskList(array $params)
    {
       return $this->mapper->getTaskList($params['uid'],$params['date'],$params['status']);
    }
    /**
     * 格式化客户数据
     * @param array $item
     * @return array
     */
    private function formattedCustomerData(array $item): array
    {

        $arr = [];
        if(!empty($item['corp_tag_ids'])){
            //企业标签
            $corpTagName = ChCorpTag::query()
                ->whereIn('id',$item['corp_tag_ids'])
                ->pluck('name')->toArray();
            $arr[] = [
                'label' => TagMathTypeConstants::getMessage($item['corp_match_type']).'企业标签',
                'value' => [
                    'text' => '',
                    'list' => $corpTagName
                ]
            ];
        }

        if(!empty($item['smart_tag_ids'])){
            //智能标签
            $smartTagName = ChSmartTag::query()
                ->whereIn('id',$item['smart_tag_ids'])
                ->pluck('name')->toArray();

            $arr[] = [
                'label' => TagMathTypeConstants::getMessage($item['smart_match_type']).'智能标签',
                'value' => [
                    'text' => '',
                    'list' => $smartTagName
                ]
            ];
        }


        //添加时间
        if(!empty($item['add_start_time']) && !empty($item['add_end_time'])){
            $arr[] = [
                'label' => '添加时间',
                'value' =>[
                    'text' => $item['add_start_time'].'至'.$item['add_end_time'],
                    'list' => []
                ]
            ];
        }

        if(isset($item['gender']) && filled($item['gender'])){
            $arr[] = [
                'label' => '性别',
                'value' => [
                    'text' =>  GenderConstants::getMessage($item['gender']),
                    'list' => []
                ]
            ];
        }

        if(isset($item['is_with_remarks']) && filled($item['is_with_remarks'])){
            if($item['is_with_remarks'] == 1){
                $remark_type = data_get($item,'remark_type',RemarkMatchTypeConstants::ALL_KEYWORD);
                $text = '有备注'.'-'.RemarkMatchTypeConstants::getMessage($remark_type);
                $list = $item['remarks'];
            }else{
                $text = '无备注';
                $list = [];
            }
            $arr[] = [
                'label' => '备注',
                'value' =>   [
                    'text' =>  $text,
                    'list' => $list
                ]
            ];
        }
        return $arr;
    }

    /**
     * 保存
     * @param array $data
     * @return mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function save(array $data): mixed
    {
        $data['send_time_config'] = $sendTimeConfig = json_decode($data['send_time_config'],true);
        $data['send_time_type'] = $sendTimeConfig['send_type'];
        $data['send_time'] = $this->getNextSendTime($sendTimeConfig);

        $fields = ['robot_ids', 'contact_data', 'send_content', 'comments'];
        foreach ($fields as $field) {
            isset($data[$field]) && $data[$field] = json_decode($data[$field], true);
        }

        if(count($data['robot_ids']) > 1){
            $config = container()->get(ChConfigService::class)->getConfigByGroupKey($data['uid'],$data['main_uid'],'friend_circle');
            $custDedup = $config['cust_dedup']['value'];
            $data['cust_dedup'] = $custDedup;
        }

        $taskId = $this->mapper->save($data);

        if ($taskId) {
            container()->get(Producer::class)->produce(new CommonProducers(new CommonProducersDto(
                classname: ChFriendCircleTaskService::class,
                method: 'sendFriendCircle',
                data: [
                    'task_id' => $taskId
                ]
            )));
        }

        return $taskId;
    }

    /**
     * 编辑任务
     * @param array $data
     * @return bool
     */
    public function updateTask(array $data): bool
    {
        $taskInfo = $this->mapper->findById($data['id']);
        if(empty($taskInfo)){
            throw new NormalStatusException('请选择您要编辑的任务');
        }

        if($taskInfo->status != FrdCircTaskStatusConstants::WAITING){
            throw new NormalStatusException('当前任务状态不允许编辑');
        }

        if(!empty($data['send_time_config'])){
            $data['send_time_config'] = $sendTimeConfig = json_decode($data['send_time_config'],true);
            $data['send_time_type'] = $sendTimeConfig['send_type'];
            $data['send_time'] = $this->getNextSendTime($sendTimeConfig);
        }

        $fields = ['robot_ids', 'contact_data', 'send_content', 'comments'];
        foreach ($fields as $field) {
            isset($data[$field]) && $data[$field] = json_decode($data[$field], true);
        }

        return $this->mapper->update($taskInfo->id,$data);
    }

    private function getNextSendTime($sendTimeConfig): float|bool|int|null
    {
        if($sendTimeConfig['send_type'] == 0){
            return time();
        }elseif ($sendTimeConfig['send_type'] == 1){
            return strtotime($sendTimeConfig['send_time']);
        }else{
            $nextSendTime = DateService::calculateNextSendTime($sendTimeConfig);
            if(!$nextSendTime){
                return null;
            }
            return $nextSendTime;
        }
    }


    /**
     * 取消任务
     * @param array $data
     * @return bool
     */
    public function cancelTask(array $data): bool
    {
        $taskInfo = $this->mapper->findById($data['id']);
        if(empty($taskInfo)){
            throw new NormalStatusException('请选择您要取消的任务');
        }

        if($taskInfo->status != FrdCircTaskStatusConstants::WAITING){
            throw new NormalStatusException('当前任务状态不允许取消');
        }

        return $this->mapper->update($taskInfo->id,[
            'status' => FrdCircTaskStatusConstants::CANCELLED
        ]);
    }

    /**
     * 删除朋友圈
     * @param array $data
     * @return bool
     */
    public function deleteFriendCircle(array $data): bool
    {
        $taskInfo = $this->mapper->findById($data['id']);
        if(empty($taskInfo)){
            throw new NormalStatusException('请选择您要删除的朋友圈');
        }

        if($taskInfo->status != FrdCircTaskStatusConstants::COMPLETED){
            throw new NormalStatusException('当前任务状态不允许删除');
        }
        $this->deleteFriendCircleJob($taskInfo->id);
        return true;
    }

    /**
     * 追加评论
     * @param array $data
     * @return bool
     */
    public function addComments(array $data): bool
    {

        $taskInfo = $this->mapper->findById($data['id']);

        if(empty($taskInfo)){
            throw new NormalStatusException('请选择您要添加评论的朋友圈');
        }

        //评论内容
        $comments = $taskInfo->comments;
        empty($comments) && $comments = [];
        $commentsCount = count($comments);

        //追加的评论数据
        $addComments = json_decode($data['comments'],true);

        foreach ($addComments as $item){
            $comments[] = $item;
        }

        $rst = $this->mapper->update($taskInfo->id,[
            'comments' => $comments
        ]);
        if(!$rst){
            return false;
        }
        $this->mapper->delCache($taskInfo->id);

        $robotIds = $taskInfo->robot_ids;

        foreach ($robotIds as $robotId) {
            $recordInfo =  ChFriendCircleTaskSendRecord::query()
                ->where('task_id',$taskInfo->id)
                ->where('robot_id',$robotId)
                ->first();

            $commentStatus = !empty($recordInfo->comment_status) ? $recordInfo->comment_status : [];
            foreach ($addComments as $k=>$item){
                $commentStatus[$commentsCount + $k] = 0;
            }
            //变更追加评论状态
            ChFriendCircleTaskSendRecord::query()
                ->where('id',$recordInfo->id)
                ->update([
                    'comment_status' => json_encode($commentStatus)
                ]);

            $robotInfo = $this->robotMapper->findById($robotId);
            if(empty($robotInfo) || $robotInfo->login_status != 1 || $recordInfo->friend_circle_status != FrdCircTaskSendStatusConstants::SUCCESS){
                continue;
            }

            $this->commentFriendCircleJob($addComments, $recordInfo->id, $robotId);
        }
        return true;
    }

    /**
     * 删除任务
     * @param array $data
     * @return bool|int|mixed|null
     * @throws \Exception
     */
    #[Transaction]
    public function deleteTask(array $data): mixed
    {
        $rst = $this->mapper->model::query()
            ->where('id',$data['id'])
            ->delete();

        if(!$rst){
            return false;
        }

        ChFriendCircleTaskSendRecord::query()
            ->where('task_id',$data['id'])
            ->delete();
        return true;
    }

    /**
     * 发送朋友圈
     * @param array $data
     * @return void
     */
    public function sendFriendCircle(array $data): void
    {
        $taskId = $data['task_id'];

        $taskInfo = $this->mapper->findById($taskId);
        if (empty($taskInfo)) {
            return;
        }

        if($taskInfo->status != FrdCircTaskStatusConstants::CREATING){
            return;
        }


        if ($taskInfo->send_time_type == 0) {
            //立即发送
            co(function () use ($taskInfo){
                try {
                    $this->sendNow($taskInfo);
                }catch (\Throwable $e){
                    logger()->info("朋友圈任务发送异常".$e->getMessage());
                }
            });
        } else {
            //定时发送
            if ($taskInfo->send_time <= time()) {
                co(function () use ($taskInfo){
                    try {
                        $this->sendNow($taskInfo);
                    }catch (\Throwable $e){
                        logger()->info("朋友圈任务发送异常".$e->getMessage());
                    }
                });
            } else {
                //待发布
                $this->mapper->update($taskInfo->id, [
                    'status' => FrdCircTaskStatusConstants::WAITING
                ]);
            }
        }
    }

    public function sendingProcess(): void
    {
        $time = time();
        $list = ChFriendCircleTask::query()
            ->where('status',FrdCircTaskStatusConstants::WAITING)
            ->where('send_time','<=',$time)
            ->get();

        foreach ($list as $taskInfo){
            co(function () use ($taskInfo){
                $this->sendNow($taskInfo);
            });
        }
    }

    /**
     * 立即发送
     * @param $taskInfo
     * @return void
     */
//    #[Transaction]
    private function sendNow(ChFriendCircleTask $taskInfo): void
    {
        //立即发送
        $robotIds = $taskInfo->robot_ids;
        //执行中
        $this->mapper->update($taskInfo->id, [
            'status' => FrdCircTaskStatusConstants::EXECUTING
        ]);

        //发布内容
        $sendContent = $taskInfo->send_content;
        //文本内容
        $content = $sendContent['text'];
        $type = $sendContent['type'];
        $material = $sendContent['data'] ?? '';

        $exceptionData = [];

        //评论内容
        $commentList = is_null($taskInfo->comments) ? [] : $taskInfo->comments;

        //定时删除
        $timingDeleteSwitch = $taskInfo->timing_delete_switch;
        $timingDeleteHour = $taskInfo->timing_delete_hour;
        $timingDeleteTime = 0;
        if($timingDeleteSwitch){
            $timingDeleteTime = Carbon::now()->addHours((int)$timingDeleteHour)->timestamp;
        }

        //成功数量
        $successCount = 0;
        $sendInterval = $taskInfo->send_interval;
        if(empty($sendInterval)){
            $sendInterval = rand(2,6);
        }

        foreach ($robotIds as $robotId) {
            $snsId = '';
            $robotInfo = $this->robotMapper->findById($robotId);

            if (empty($robotInfo)) {
                continue;
            }

            if ($robotInfo->login_status != 1) {
                //机器人离线
                $friendCircleStatus = FrdCircTaskSendStatusConstants::FAILURE;
                $exceptionData[] = '机器人离线';
            } else {
                //调用真实发送的接口
                $robotApiService = make(Robot::class, [$robotInfo->server_id, $robotInfo->uuid])->gateway();
                $materialList = [];
                $linkInfo = [];
                $postType = 0;
                switch ($type) {
                    case FrdCircTaskContentTypeConstants::IMAGE:
                        //图片
                        try {
                            $materialList = $this->getImgMaterial($robotApiService, $material);
                        }catch (\Throwable $e){
                            logger()->info("朋友圈任务发送图片-异常".$e->getMessage());
                        }
                        break;
                    case FrdCircTaskContentTypeConstants::VIDEO:
                        //视频
                        $materialList = $this->getVideoMaterial($robotApiService, $material);
                        break;
                    case FrdCircTaskContentTypeConstants::LINK:
                        //链接
                        $linkInfo = $this->getUrlLinkInfo($material);
                        $materialList = $this->getUrlMaterial($robotApiService, $material);
                        $postType = 1;
                        break;
                    case FrdCircTaskContentTypeConstants::VIDEO_CHANNEL:
                        //视频号
                        $linkInfo = $this->getVideoChannelLinkInfo($material);
                        $materialList = $this->getVideoChannelMaterial($robotApiService, $material);
                        $postType = 1;
                    default:
                        break;
                }
                //可见用户
                if($taskInfo->contact_data['type'] == 2){
                    $visibleUserIdList = container()->get(ChCrowSendingService::class)->getContactList($robotId,$taskInfo->uid,$taskInfo->contact_data);
                }else{
                    $visibleUserIdList = [];
                }
                $materialList = underToCamel($materialList);
                $linkInfo = underToCamel($linkInfo);
                $result = $robotApiService->postSns($postType, $content, $materialList, $linkInfo, $visibleUserIdList);
                if ($result === false) {
                    $friendCircleStatus = FrdCircTaskSendStatusConstants::FAILURE;
                    $exceptionData[] = $robotApiService->getErrorMsg();
                } else {
                    $friendCircleStatus = FrdCircTaskSendStatusConstants::SUCCESS;
                    //朋友圈ID
                    $snsId = $result['sns_detail']['sns_id'];
                    $successCount = $successCount + 1;
                }
            }

            $commentStatus = [];
            foreach ($commentList as $k=>$item){
                $commentStatus[$k] = 0;
            }

            $sendRecord = [
                'task_id' => $taskInfo->id,
                'robot_id' => $robotId,
                'friend_circle_status' => $friendCircleStatus,
                'comment_status' => json_encode($commentStatus),
                'sns_id' => $snsId,
                'timing_delete_switch' => $timingDeleteSwitch,
                'timing_delete_hour' => $timingDeleteHour,
                'timing_delete_time' => $timingDeleteTime,//定时删除时间
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString(),
            ];

            $recordId = ChFriendCircleTaskSendRecord::insertGetId($sendRecord);
            if ($friendCircleStatus == FrdCircTaskSendStatusConstants::SUCCESS && !empty($commentList)) {
                $this->commentFriendCircleJob($commentList, $recordId, $robotId);
            }

            Coroutine::sleep($sendInterval);
        }

        $updateData['publish_time'] = time();
        $updateData['exception_data'] = $exceptionData;
        if($taskInfo->send_time_type == 0 || $taskInfo->send_time_type == 1){
            $updateData['status'] = FrdCircTaskStatusConstants::COMPLETED;
        }else{
            $sendTimeConfig = $taskInfo->send_time_config;
            $nextSendTime = $this->getNextSendTime($taskInfo->send_time_config);
            if($sendTimeConfig['isLoopEnded'] == 1){
                $endTime = strtotime($sendTimeConfig['end_time']);
                if($nextSendTime > $endTime){
                    $status = FrdCircTaskStatusConstants::COMPLETED;
                }else{
                    $status = FrdCircTaskStatusConstants::WAITING;
                }
            }else{
                $status = FrdCircTaskStatusConstants::WAITING;
            }
            $updateData['status'] = $status;
            if($status == FrdCircTaskStatusConstants::WAITING){
                $updateData['send_time'] = $nextSendTime;
            }
        }
        //发布完成
        $this->mapper->update($taskInfo->id,$updateData);
    }

    private function commentFriendCircleJob($commentList, $recordId, $robotId): void
    {
        //评论间隔
        $commentInterval = 0;
        $totalComment = count($commentList);
        foreach ($commentList as $k=>$item) {
            $unit = $item['unit'] ?? 0;
            $delay = $item['delay'] ?? 0;

            if ($unit == 0) {
                $delay = $delay * 60;
            }
            $commentInterval += $delay;
            //延迟评论
            $driver = container()->get(DriverFactory::class)->get('low_priority');
            $job = new CommonJob(new CommonJobDto(
                classname: ChFriendCircleTaskService::class,
                method: 'postComment',
                data: [
                    'record_id' => $recordId,
                    'robot_id' => $robotId,
                    'content' => $item['text'],
                    'index' => $k,
                    'is_last' => $k+1 == $totalComment//是否最后一条
                ]
            ));
            $driver->push($job, $commentInterval);
        }
    }

    /**
     * 发布评论
     * @param array $data
     * @return void
     */
    public function postComment(array $data): void
    {
        $recordId = $data['record_id'];
        $content = $data['content'];
        $robotId = $data['robot_id'];
        $index = $data['index'] ?? 0;
        $isLast = $data['is_last'] ?? false;
        if(empty($recordId) || empty($content) || empty($robotId)){
            return;
        }

        $recordInfo = ChFriendCircleTaskSendRecord::query()->where('id', $recordId)
            ->first();
        $commentStatus = !empty($recordInfo->comment_status) ? $recordInfo->comment_status : [];
        if (!empty($recordInfo)) {

            $robotInfo = $this->robotMapper->findById($robotId);

            if (!empty($robotInfo) && $robotInfo->login_status == 1) {
                $robotApiService = make(Robot::class, [$robotInfo->server_id, $robotInfo->uuid])->gateway();
                $result = $robotApiService->snsComment((int)$recordInfo->sns_id, $content);
                if ($result !== false) {
                    $commentStatus[$index] = FrdCircTaskSendStatusConstants::SUCCESS;
                    //获取朋友圈详情
                    $detailList = $robotApiService->getSnsDetail([(int)$recordInfo->sns_id]);
                    $detail = array_shift($detailList['sns_detail_list']);
                    $commentList = $detail['comment_list'];
                    $userId = $robotInfo->user_id;
                    //获取评论ID
                    $commentIds = collect($commentList)->filter(function ($item) use ($userId) {
                        return $item['comment_from_id'] == $userId;
                    })->pluck('comment_id')->toArray();

                    ChFriendCircleTaskSendRecord::query()->where('id', $recordId)->update([
                        'comment_status' => json_encode($commentStatus),
                        'comment_id' => json_encode($commentIds)
                    ]);

//                    if($recordInfo->timing_delete_switch && $isLast){
//
//                        //定时删除开启，且最后一条评论的情况
//                        $this->deleteFriendCircleJob($recordInfo->task_id,$recordInfo->timing_delete_hour * 3600);
//                    }
                    $timingDeleteTime = $recordInfo->timing_delete_time;
                    if($recordInfo->timing_delete_switch){
                        //定时删除需要更新删除时间
                        $timingDeleteTime = Carbon::now()->addHours($recordInfo->timing_delete_hour)->timestamp;
                    }

                    ChFriendCircleTaskSendRecord::query()->where('id', $recordId)->update([
                        'comment_status' => json_encode($commentStatus),
                        'comment_id' => json_encode($commentIds),
                        'timing_delete_time' => $timingDeleteTime,
                    ]);
                }else{
                    $commentStatus[$index] = FrdCircTaskSendStatusConstants::FAILURE;
                    ChFriendCircleTaskSendRecord::query()->where('id', $recordId)->update([
                        'comment_status' => json_encode($commentStatus),
                    ]);
                }
            }
        }
    }


    private function deleteFriendCircleJob(mixed $taskId,int $delay = 0)
    {
        $driver = container()->get(DriverFactory::class)->get('low_priority');
        $job = new CommonJob(new CommonJobDto(
            classname: ChFriendCircleTaskService::class,
            method: 'realDeleteFriendCircle',
            data: [
                'task_id' => $taskId,
            ]
        ));
        $driver->push($job, $delay);
    }

    /**
     * 真实删除朋友圈
     * @param array $data
     * @return void
     */
    public function realDeleteFriendCircle(array $data): void
    {
        if(empty($data['task_id'])){
            return;
        }

        $taskId = $data['task_id'];

        $recordList = ChFriendCircleTaskSendRecord::query()
            ->where('task_id',$taskId)
            ->where('friend_circle_status',FrdCircTaskSendStatusConstants::SUCCESS)
            ->get();
        foreach ($recordList as $record){
            $robotInfo = $this->robotMapper->findById($record->robot_id);
            if(empty($robotInfo || $robotInfo->login_status != 1)){
                continue;
            }
            $robotApiService = make(Robot::class, [$robotInfo->server_id, $robotInfo->uuid])->gateway();
            $response = $robotApiService->deleteSns((int)$record->sns_id);
            if($response === false){
                logger()->info("删除朋友圈失败task_id:".$taskId.'-'.$robotApiService->getErrorMsg());
                continue;
            }
            ChFriendCircleTaskSendRecord::query()
                ->where('id',$record->id)
                ->update([
                    'friend_circle_status' => FrdCircTaskSendStatusConstants::DELETE
                ]);
        }
    }

    /**
     * 获取图片素材
     * @param GatewayInterface $robotApiService
     * @param array $img
     * @return array
     */
    private function getImgMaterial(GatewayInterface $robotApiService, array $img): array
    {
        if (empty($img)) {
            return [];
        }
        $materialList = $this->coDeal($img, function ($item) use ($robotApiService) {
            $rst = $robotApiService->snsUpload($item,1);
            if($rst === false){
                return [];
            }
            return $rst;
        });

        if(empty($materialList)){
            return [];
        }

        $newList = [];
        foreach ($materialList as $k => $item) {
            if(!empty($item)){
                $item['file_width'] = 64;
                $item['file_height'] = 48;
                $item['file_type'] = 1;
                unset($item['file_key'], $item['file_md5']);
                $newList[] = $item;
            }
        }
        return $newList;
    }

    /**
     * 获取视频素材
     * @param GatewayInterface $robotApiService
     * @param string $videoUrl
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    private function getVideoMaterial(GatewayInterface $robotApiService, string $videoUrl): array
    {
        if (empty($videoUrl)) {
            return [];
        }
        $materialList = [];
        $videoHelper = container()->get(VideoHelper::class);
        //视频封面
        $videoCover = $videoHelper->getVideoCover($videoUrl);
        //视频时长
        $videoDuration = $videoHelper->getVideoDuration($videoUrl);

        $videoMaterialInfo = $robotApiService->snsUpload($videoUrl,2);
        $videoMaterialInfo['file_type'] = 2;
        $videoMaterialInfo['video_length'] = $videoDuration;
        $videoMaterialInfo['file_width'] = 64;
        $videoMaterialInfo['file_height'] = 48;
        $materialList[] = $videoMaterialInfo;
        $videoCoverMaterialInfo = $robotApiService->snsUpload($videoCover,3);
        $videoCoverMaterialInfo['file_type'] = 3;
        $videoCoverMaterialInfo['file_width'] = 64;
        $videoCoverMaterialInfo['file_height'] = 48;
        $materialList[] = $videoCoverMaterialInfo;
        return $materialList;
    }

    /**
     * 获取链接信息
     * @param array $urlData
     * @return array
     */
    private function getUrlLinkInfo(array $urlData): array
    {
        return [
            'title' => $urlData['title'],
            'contentUrl' => $urlData['url'],
        ];
    }

    /**
     * 获取链接素材
     * @param GatewayInterface $robotApiService
     * @param array $urlData
     * @return array
     */
    private function getUrlMaterial(GatewayInterface $robotApiService, array $urlData): array
    {
        $material = $robotApiService->snsUpload($urlData['cover'],1);
        $material['file_width'] = 64;
        $material['file_height'] = 48;
        $material['file_type'] = 1;
        unset($material['file_key'], $material['file_md5']);
        return [$material];
    }

    /**
     * 获取视频号信息
     * @param array $videoChannelData
     * @return array
     */
    private function getVideoChannelLinkInfo(array $videoChannelData): array
    {
        return [
            'title' => $videoChannelData['channel_name'],
            'contentUrl' => $videoChannelData['channel_url'],
            'wxFinderInfo' => [
                'avatar' => $videoChannelData['head_img_url'],
                'coverUrl' => $videoChannelData['cover_url'],
                'desc' => '',
                'extras' => $videoChannelData['encode_data'],
                'feedType' => 4,
                'nickname' => $videoChannelData['username'],
                'ThumbUrl' => $videoChannelData['cover_url'],
                'Url' => $videoChannelData['channel_url']
            ]
        ];
    }

    /**
     * 获取视频号素材
     * @param GatewayInterface $robotApiService
     * @param array $videoChannelData
     * @return array
     */
    private function getVideoChannelMaterial(GatewayInterface $robotApiService, array $videoChannelData): array
    {
        if (empty($videoChannelData['wxFinderInfo']['coverUrl'])) {
            return [];
        }
        $material = $robotApiService->snsUpload($videoChannelData['wxFinderInfo']['coverUrl'],1);
        if($material === false){
            return [];
        }
        $material['fileWidth'] = 64;
        $material['fileHeight'] = 48;
        $material['fileType'] = 1;
        unset($material['fileKey'], $material['fileMd5'], $material['cloudUrl']);
        return [$material];
    }

    /**
     * 协程请求
     * @return array
     */
    protected function coDeal(array $arr, \Closure $call)
    {
        $parallel = new Parallel();
        foreach ($arr as $item) {
            $parallel->add(function () use ($item, $call) {
                return $call($item);
            });
        }

        $results = [];
        try {
            $results = $parallel->wait();
        } catch (ParallelExecutionException $e) {
            logger()->error($e->getMessage());
            // $e->getResults() 获取协程中的返回值。
            // $e->getThrowables() 获取协程中出现的异常。
        }
        return $results;
    }

    private function formattingParameters()
    {

    }
}